// sm2g_2.c
#include <stdio.h>
#include <string.h>
#include <gmssl/sm2.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#ifndef SM2_MAX_SIGNATURE_SIZE
#define SM2_MAX_SIGNATURE_SIZE 72
#endif

int main() {
    uint8_t msg[] = "This is 20231318fsl making SM2 signature.";
    size_t msg_len = strlen((char*)msg);

    uint8_t dgst[32];  // SM3 摘要固定 32 字节
    uint8_t sig[SM2_MAX_SIGNATURE_SIZE];
    size_t sig_len = sizeof(sig);

    // Step 1: 使用 EVP 计算 SM3 摘要
    EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
    if (!md_ctx) {
        fprintf(stderr, "EVP_MD_CTX_new failed\n");
        return 1;
    }

    if (EVP_DigestInit_ex(md_ctx, EVP_sm3(), NULL) != 1 ||
        EVP_DigestUpdate(md_ctx, msg, msg_len) != 1 ||
        EVP_DigestFinal_ex(md_ctx, dgst, NULL) != 1) {
        fprintf(stderr, "SM3 digest failed\n");
        EVP_MD_CTX_free(md_ctx);
        return 1;
    }
    EVP_MD_CTX_free(md_ctx);

    // Step 2: 生成 SM2 密钥
    SM2_KEY key;
    if (sm2_key_generate(&key) != 1) {
        fprintf(stderr, "SM2 key generation failed\n");
        return 1;
    }

    // Step 3: 对摘要签名
    if (sm2_sign(&key, dgst, sig, &sig_len) != 1) {
        fprintf(stderr, "SM2 sign failed\n");
        return 1;
    }
    printf("SM2 sign success, sig len = %zu\n", sig_len);

    // Step 4: 验签
    if (sm2_verify(&key, dgst, sig, sig_len) != 1) {
        fprintf(stderr, "SM2 verify failed\n");
        return 1;
    }
    printf("SM2 verify success\n");

    return 0;
}
